from flask import Flask, request, jsonify
import psycopg2
from psycopg2 import pool

app = Flask(__name__)

# PostgreSQL连接池配置
db_pool = psycopg2.pool.SimpleConnectionPool(
    1,  # 最小连接数
    10, # 最大连接数
    host="localhost",
    database="postgres",
    user="postgres",
    password="123456"
)

@app.route('/api/profile')
def get_profile():
    student_id = request.args.get('student_id')
    if not student_id:
        return jsonify({'code': 1, 'msg': '缺少学生ID参数'})
    
    try:
        # 从连接池获取连接
        conn = db_pool.getconn()
        cursor = conn.cursor()
        
        # 从student_basic_info表获取数据
        cursor.execute("""
            SELECT * FROM student_basic_info 
            WHERE student_id = %s
        """, (student_id,))
        result = cursor.fetchone()
        
        # 释放连接回连接池
        cursor.close()
        db_pool.putconn(conn)
        
        if result:
            # 将结果转换为字典
            data = {
                'student_id': result[0],
                'name': result[1],
                'gender': result[2],
                'birthday': result[3].strftime('%Y-%m-%d') if result[3] else None,
                'id_card': result[4],
                'nation': result[5],
                'political_status': result[6],
                'education': result[7],
                'major': result[8],
                'enrollment_year': result[9],
                'graduation_year': result[10],
                'phone': result[11],
                'email': result[12],
                'address': result[13],
                'emergency_contact': result[14],
                'emergency_phone': result[15]
            }
            return jsonify({'code': 0, 'msg': '获取成功', 'data': data})
        else:
            return jsonify({'code': 1, 'msg': '未找到学生信息'})
            
    except Exception as e:
        print(f"Error: {str(e)}")
        return jsonify({'code': 1, 'msg': '获取学生信息失败'})

if __name__ == '__main__':
    app.run(debug=True) 